package com.personalink.input.controller;

import com.personalink.common.dto.ApiResponse;
import com.personalink.common.dto.ChatRequest;
import com.personalink.input.dto.InputProcessResult;
import com.personalink.input.service.ImageProcessService;
import com.personalink.input.service.TextProcessService;
import com.personalink.input.service.VoiceProcessService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 多模态输入处理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/input")
@RequiredArgsConstructor
@Validated
public class InputController {
    
    private final TextProcessService textProcessService;
    private final ImageProcessService imageProcessService;
    private final VoiceProcessService voiceProcessService;
    
    /**
     * 处理文本输入
     */
    @PostMapping("/text")
    public ApiResponse<InputProcessResult> processText(
            @Valid @RequestBody ChatRequest request) {
        
        log.info("处理文本输入，用户ID: {}, 会话ID: {}", request.getUserId(), request.getSessionId());
        
        InputProcessResult result = textProcessService.processText(request);
        
        return ApiResponse.success(result);
    }
    
    /**
     * 处理图像输入
     */
    @PostMapping(value = "/image", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ApiResponse<InputProcessResult> processImage(
            @RequestParam("file") @NotNull MultipartFile file,
            @RequestParam("userId") @NotBlank String userId,
            @RequestParam("sessionId") @NotBlank String sessionId,
            @RequestParam(value = "description", required = false) String description) {
        
        log.info("处理图像输入，用户ID: {}, 会话ID: {}, 文件大小: {} bytes", 
                userId, sessionId, file.getSize());
        
        InputProcessResult result = imageProcessService.processImage(file, userId, sessionId, description);
        
        return ApiResponse.success(result);
    }
    
    /**
     * 处理语音输入
     */
    @PostMapping(value = "/voice", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ApiResponse<InputProcessResult> processVoice(
            @RequestParam("file") @NotNull MultipartFile file,
            @RequestParam("userId") @NotBlank String userId,
            @RequestParam("sessionId") @NotBlank String sessionId,
            @RequestParam(value = "language", defaultValue = "zh-CN") String language) {
        
        log.info("处理语音输入，用户ID: {}, 会话ID: {}, 文件大小: {} bytes, 语言: {}", 
                userId, sessionId, file.getSize(), language);
        
        InputProcessResult result = voiceProcessService.processVoice(file, userId, sessionId, language);
        
        return ApiResponse.success(result);
    }
    
    /**
     * 处理混合模态输入
     */
    @PostMapping(value = "/multimodal", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ApiResponse<InputProcessResult> processMultimodal(
            @RequestParam("userId") @NotBlank String userId,
            @RequestParam("sessionId") @NotBlank String sessionId,
            @RequestParam(value = "text", required = false) String text,
            @RequestParam(value = "image", required = false) MultipartFile image,
            @RequestParam(value = "voice", required = false) MultipartFile voice,
            @RequestParam(value = "language", defaultValue = "zh-CN") String language) {
        
        log.info("处理混合模态输入，用户ID: {}, 会话ID: {}", userId, sessionId);
        
        // 构建聊天请求
        ChatRequest request = ChatRequest.builder()
                .userId(userId)
                .sessionId(sessionId)
                .inputType(text)
                //todo 更改
//                .textContent(text)
                .build();
        
        InputProcessResult result = new InputProcessResult();
        result.setUserId(userId);
        result.setSessionId(sessionId);
        result.setInputType("multimodal");
        
        // 处理文本
        if (text != null && !text.trim().isEmpty()) {
            InputProcessResult textResult = textProcessService.processText(request);
            result.setProcessedText(textResult.getProcessedText());
            result.setTextAnalysis(textResult.getTextAnalysis());
        }
        
        // 处理图像
        if (image != null && !image.isEmpty()) {
            InputProcessResult imageResult = imageProcessService.processImage(image, userId, sessionId, null);
            result.setImageAnalysis(imageResult.getImageAnalysis());
            result.setExtractedObjects(imageResult.getExtractedObjects());
        }
        
        // 处理语音
        if (voice != null && !voice.isEmpty()) {
            InputProcessResult voiceResult = voiceProcessService.processVoice(voice, userId, sessionId, language);
            result.setTranscribedText(voiceResult.getTranscribedText());
            result.setVoiceAnalysis(voiceResult.getVoiceAnalysis());
        }
        
        result.setProcessedAt(System.currentTimeMillis());
        
        return ApiResponse.success(result);
    }
    
    /**
     * 获取支持的输入格式
     */
    @GetMapping("/formats")
    public ApiResponse<Object> getSupportedFormats() {
        return ApiResponse.success(java.util.Map.of(
                "text", java.util.Map.of(
                        "maxLength", 10000,
                        "supportedLanguages", java.util.Arrays.asList("zh-CN", "en-US", "ja-JP")
                ),
                "image", java.util.Map.of(
                        "supportedFormats", java.util.Arrays.asList("jpg", "jpeg", "png", "gif", "webp"),
                        "maxSize", "10MB",
                        "maxDimensions", "4096x4096"
                ),
                "voice", java.util.Map.of(
                        "supportedFormats", java.util.Arrays.asList("mp3", "wav", "m4a", "ogg"),
                        "maxSize", "50MB",
                        "maxDuration", "300s",
                        "supportedLanguages", java.util.Arrays.asList("zh-CN", "en-US", "ja-JP")
                )
        ));
    }
}